package com.linewow.xhyy.nihaonew.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.tutu.FilterEditorSampleActivity;
import com.linewow.xhyy.nihaonew.adapter.NewTopicAdapter;
import com.linewow.xhyy.nihaonew.base.BaseActivity;
import com.linewow.xhyy.nihaonew.entity.NewTopicImageInfo;
import com.linewow.xhyy.nihaonew.entity.data.NewTopicData;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.helper.GlideImageLoader;
import com.linewow.xhyy.nihaonew.helper.ItemDragHelperCallback;
import com.linewow.xhyy.nihaonew.helper.VoiceMenuHelper;
import com.linewow.xhyy.nihaonew.model.AppConstants;
import com.linewow.xhyy.nihaonew.util.CommonUtil;
import com.linewow.xhyy.nihaonew.view.VoiceButton1;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.lasque.tusdk.core.TuSdk;
import org.lasque.tusdk.core.secret.StatisticsManger;
import org.lasque.tusdk.core.seles.tusdk.FilterManager;
import org.lasque.tusdk.modules.components.ComponentActType;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/9/21.
 * /storage/emulated/0/NiHao/test20160925T110628.amr
 */
public class NewTopicActivity extends BaseActivity {
    @Bind(R.id.toolbar_find_title)
    TextView toolbarFindTitle;
    @Bind(R.id.toolbar_find_left)
    ImageView toolbarFindLeft;
    @Bind(R.id.toolbar_find_right)
    ImageView toolbarFindRight;
    @Bind(R.id.toolbar_find_right_tv)
    TextView toolbarFindRightTv;
    @Bind(R.id.toolbar_find_toolbar)
    Toolbar toolbarFindToolbar;
    @Bind(R.id.new_subject_edit)
    EditText newSubjectEdit;
    @Bind(R.id.new_recycler)
    RecyclerView newRecycler;
    @Bind(R.id.new_add_image)
    ImageView newAddImage;
    @Bind(R.id.new_location_image)
    ImageView newLocationImage;
    @Bind(R.id.new_location_tv)
    TextView newLocationTv;
    @Bind(R.id.new_location_rela)
    RelativeLayout newLocationRela;
    @Bind(R.id.new_voice_btn)
    VoiceButton1 newVoiceBtn;
    @Bind(R.id.new_voice_rela)
    RelativeLayout newVoiceRela;
    @Bind(R.id.new_add_voice)
    ImageView newAddVoice;
    @Bind(R.id.new_add_website)
    ImageView newAddWebsite;
    @Bind(R.id.new_website_rela)
    RelativeLayout newWebsiteRela;
    @Bind(R.id.new_website_edit)
    EditText newWebsiteEdit;
    @Bind(R.id.new_website_del)
    TextView newWebsiteDel;
    @Bind(R.id.new_mask)
    RelativeLayout newMask;
    @Bind(R.id.new_edit)
    TextView newEdit;
    private NewTopicAdapter adapter;
    private List<NewTopicImageInfo>paths;

    private String TAG="NewTopicActivity";
    private VoiceMenuHelper voiceMenuHelper;
    private boolean voiceFlag,linkFlag;
    private String voicePath;
    private int voiceLength;
    private ArrayList<ImageItem> images;
    private String poiLocation;
    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_new_topic);
        ButterKnife.bind(this);
        EventBus.getDefault().register(NewTopicActivity.this);
        voiceMenuHelper=new VoiceMenuHelper(NewTopicActivity.this,toolbarFindLeft,TAG);
        toolbarFindRight.setVisibility(View.GONE);
        toolbarFindRightTv.setVisibility(View.VISIBLE);
        toolbarFindRightTv.setText(getString(R.string.widget_next));
        toolbarFindTitle.setText(getString(R.string.title_new));
        toolbarFindLeft.setImageResource(R.mipmap.icon_back_white);
        newEdit.setSelected(false);
    }

    @Override
    public void initList() {
        super.initList();
        paths=new ArrayList<NewTopicImageInfo>();
        adapter=new NewTopicAdapter(paths);
        LinearLayoutManager manager=new LinearLayoutManager(NewTopicActivity.this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        newRecycler.setLayoutManager(manager);
        newRecycler.setItemAnimator(new DefaultItemAnimator());
        newRecycler.setAdapter(adapter);
        adapter.getHelper().attachToRecyclerView(newRecycler);
        newMask.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }
        });

        newRecycler.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void SimpleOnItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (view.getId()){
                    case R.id.item_new_topic_image:

                        String path=paths.get(i).path;
                        Log.e("NewTopicActivity","点击图片"+path);
                        Intent tuIntent=new Intent(NewTopicActivity.this, FilterEditorSampleActivity.class);
                        tuIntent.putExtra("path",path);
                        tuIntent.putExtra("index",i);
                        startActivityForResult(tuIntent,10);

                        break;
                    case R.id.item_new_topic_del:
                        Log.e("NewTopicActivity","点击删除");
                        adapter.remove(i);
                        break;
                }
            }
        });
        newRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                Log.e("NewTopicActivity","点击编辑");
            }
        });

        StatisticsManger.appendComponent(ComponentActType.sdkComponent);

        // 异步方式初始化滤镜管理器 (注意：如果需要一开启应用马上执行SDK组件，需要做该检测，否则可以忽略检测)
        // 需要等待滤镜管理器初始化完成，才能使用所有功能
        TuSdk.messageHub().setStatus(NewTopicActivity.this, R.string.lsq_initing);
        TuSdk.checkFilterManager(mFilterManagerDelegate);
    }


    @OnClick({R.id.toolbar_find_left, R.id.toolbar_find_right_tv,
            R.id.new_add_image,R.id.new_add_voice,R.id.new_add_website,R.id.new_voice_del,
            R.id.new_website_del,R.id.new_location_rela,R.id.new_edit})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.toolbar_find_left:
//                Intent intent1=new Intent(NewTopicActivity.this, ZActivity.class);
//                startActivity(intent1);
//                showLoading();//这一个不显示？？？
                finish();
                break;
            case R.id.toolbar_find_right_tv:
                checkData();
                break;
            case R.id.new_add_image:


                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new GlideImageLoader());
                imagePicker.setMultiMode(true);   //多选true
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(false);
                imagePicker.setSelectLimit(30);
                Intent imageIntent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(imageIntent, 4);

                break;

            case R.id.new_add_voice:
                Log.e(TAG,"开启菜单");
                if(!voiceFlag){
                    voiceMenuHelper.show();
                }
                break;
            case R.id.new_add_website:
                linkFlag=true;
                updateView();
                break;
            case R.id.new_voice_del:
                boolean delVoiceFlag=voiceMenuHelper.delVoiceFile();//删除成功了
                if(delVoiceFlag){
                    voiceFlag=false;
                    updateView();
                    voicePath=null;
                }
                break;
            case R.id.new_website_del:
                linkFlag=false;
                updateView();
                break;

            case R.id.new_location_rela:

                Log.e(TAG,"点击所在位置");
//                Intent poiIntent=new Intent(NewTopicActivity.this,POIActivity.class);
//                startActivityForResult(poiIntent, 111);

                break;

            case R.id.new_edit:
                Log.e(TAG,"被点击了");
                boolean selectFlag=newEdit.isSelected();
                if(selectFlag){
                    Log.e(TAG,"完成了");
                    newEdit.setText("编辑");
                    selectFlag=!selectFlag;
                }else{
                    Log.e(TAG,"编辑了");
                    newEdit.setText("完成");
                    selectFlag=!selectFlag;
                }
                newEdit.setSelected(selectFlag);
                if(paths.size()>0){
                    adapter.setEditFlag(selectFlag);
                }
                break;
        }
    }

    private void checkData() {
        Bundle bundle=new Bundle();
        NewTopicData data=new NewTopicData();
        String subjectStr=newSubjectEdit.getText().toString();
        if(subjectStr.length()<2){
            showCanDialog(getString(R.string.intelligent_no_subject));
            return;
        }
        if(paths.size()==0){
            showCanDialog(getString(R.string.intelligent_no_pic));
            return;
        }
        data.subject=subjectStr;

        List<String>list=new ArrayList<String>();
        String pathsJson="[";
        StringBuilder stringBuilder=new StringBuilder(pathsJson);
        for(int i=0;i<paths.size();i++){
            NewTopicImageInfo info=paths.get(i);
            list.add(info.path);
            if(i!=0){
                stringBuilder.append(",");
            }
            if(info.description==null){
                stringBuilder.append("\"\"");
            }else{
                stringBuilder.append("\""+info.description+"\"");
            }
        }
        stringBuilder.append("]");
        data.paths=list;
        data.pathsJson=stringBuilder.toString();
        if(voicePath!=null){
            voiceLength= Integer.parseInt(CommonUtil.getLength(voicePath));
            data.voiceLength=voiceLength;
            data.voicePath=voicePath;
        }

        if(linkFlag){
            String website=newWebsiteEdit.getText().toString();
            if(website.length()>5){
                data.website=website;
            }
        }
        bundle.putParcelable("data",data);
        Intent intent=new Intent(NewTopicActivity.this,NewCommitActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent,10);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 4) {
                 images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Observable.just(images)
                        .map(new Func1<List<ImageItem>, List<NewTopicImageInfo>>() {
                            @Override
                            public List<NewTopicImageInfo> call(List<ImageItem> imageItems) {
                                return imageItemToNewTopicImageInfo(imageItems);
                            }
                        })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<List<NewTopicImageInfo>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(List<NewTopicImageInfo> newTopicImageInfos) {
                                int size1=paths.size();
                                int size2=images.size();
                                paths.addAll(newTopicImageInfos);
                                Log.e(TAG,"现在的大小"+paths.size()+"size1"+size1+"size2"+size2);
                                adapter.notifyItemRangeInserted(size1,size2);
                            }
                        });
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if(requestCode==10&&resultCode==RESULT_OK){
            finish();
        }else if(resultCode==AppConstants.POICODE){
            String newLocation=data.getStringExtra("poi");
            if(newLocation.equals("")){
                poiLocation=null;
                newLocationTv.setText(getString(R.string.new_location));
            }else{
                poiLocation=newLocation;
                newLocationTv.setText(poiLocation);
            }
        }else if(requestCode==10&&resultCode==11){
            int index=data.getIntExtra("index",0);
            String path=data.getStringExtra("path");
            Log.e(TAG,"index"+index+"---"+path);
            NewTopicImageInfo info=paths.get(index);
            info.setPath(path);
            paths.set(index,info);
            adapter.notifyItemChanged(index);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public List<NewTopicImageInfo> StringToNewTopicImageInfo(List<String>paths){
        List<NewTopicImageInfo>infos=new ArrayList<NewTopicImageInfo>();
        for(String temp:paths){
            NewTopicImageInfo info=new NewTopicImageInfo(temp);
            infos.add(info);
        }
        return infos;
    }
    public List<NewTopicImageInfo> imageItemToNewTopicImageInfo(List<ImageItem>paths){
        List<NewTopicImageInfo>infos=new ArrayList<NewTopicImageInfo>();
        for(ImageItem temp:paths){
            Log.e(TAG,"名称--->"+temp.path);
            NewTopicImageInfo info=new NewTopicImageInfo(temp.path);
            infos.add(info);
        }
        return infos;
    }



    @Subscriber(tag = "NewTopicActivity", mode = ThreadMode.MAIN)
    public void onAdapterClick(NewTopicImageInfo info) {
        int i=paths.indexOf(info);
        Log.e(TAG,"删除第"+i);
        paths.remove(i);
        adapter.notifyItemRemoved(i);
    }


    @Subscriber(tag = "NewTopicActivity",mode = ThreadMode.MAIN)
    public void onVoiceChoose(MessageEvent messageEvent){
        String path=messageEvent.getMessage();
        Log.e(TAG,"路径"+path);
        voicePath=path;
        newVoiceBtn.setPath(voicePath);
        voiceFlag=true;
        updateView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().register(NewTopicActivity.this);
    }

    public void updateView(){
        if(voiceFlag){
            newAddVoice.setImageResource(R.drawable.icon_mic_circle_gray);
            newVoiceRela.setVisibility(View.VISIBLE);

        }else{
            newAddVoice.setImageResource(R.drawable.icon_mic_circle_white);
            newVoiceRela.setVisibility(View.GONE);
        }
        if(linkFlag){
            newAddWebsite.setImageResource(R.drawable.icon_website_circle_gray);
            newWebsiteRela.setVisibility(View.VISIBLE);
        }else{
            newAddWebsite.setImageResource(R.drawable.icon_website_circle_white);
            newWebsiteRela.setVisibility(View.GONE);
        }
    }


    /** 滤镜管理器委托 */
    private FilterManager.FilterManagerDelegate mFilterManagerDelegate = new FilterManager.FilterManagerDelegate()
    {
        @Override
        public void onFilterManagerInited(FilterManager manager)
        {
            Log.e(TAG,"初始化完成了");
            TuSdk.messageHub().showSuccess(NewTopicActivity.this, R.string.lsq_inited);
        }
    };
}
